package RMI;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import Entidades.Filial;
import Entidades.Projeto;
import Util.Controle;

public class Cliente {
	private static IFilial[] conexao;
	private static Timer timer;

	public static IFilial[] getConexao() {

		if (conexao == null) {
			conexao = new IFilial[11];
		}

		if (timer == null) {
			timer = new Timer();

			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					System.out.println("\n\n");
					refreshConexao();
				}
			}, 0, 6000);
		}

		return conexao;
	}
	

	public static void refreshConexao() {
		for (int i = 1; i <= 10; i++) {
			
			conecta(i);
		}
	}

	private static void conecta(int n) {

		try {

			
			conexao[n] = (IFilial) Naming.lookup(Controle.getServerAddress(n));
			System.out.println(" * Filial Online * "+ Controle.getServerAddress(n) + " "+ conexao[n].ping());

		} catch (NotBoundException ex) {
			System.out.println(" NotBoundException "
					+ Controle.getServerAddress(n));

		} catch (RemoteException e) {
			System.out.println(" RemoteException "
					+ Controle.getServerAddress(n));
			conexao[n] = null;

		} catch (MalformedURLException e) {
			System.out.println(" MalformedURLException "
					+ Controle.getServerAddress(n));
		}

	}

	public static String ListaOnline() {
		String s = "<html>";
		for (int i = 1; i <= 10; i++) {

			if (conexao[i] != null)
				s = s + "<FONT COLOR=#00FF00> &nbsp; F" + i + "</FONT>";
			else
				s = s + "<FONT COLOR=BLACK> &nbsp; F" + i + "</FONT>";
		}
		s = s + "</html>";
		return s;
	}
	
	
	public static ArrayList<Projeto> getProjetos() throws RemoteException {
		ArrayList<Projeto> listaProjetos = new ArrayList<Projeto>();
	
		for (int i = 1; i <= 10; i++) {

			if (conexao[i] != null) {
					listaProjetos.addAll(conexao[i].listaProjetos());
					
				}
			}
		return listaProjetos;
				
				
		}
}
